package com.iweb.listener;

import com.alibaba.fastjson.JSON;
import com.iweb.common.result.ResultEntity;
import com.iweb.netty.NoticeWebSocketHandler;
import com.rabbitmq.client.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

//用户在线的时候，实时消费消息并推送
@Component
public class SysNoticeListener implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 通过队列名称 article_subscribe_2 获取用户id
        String queueName = message.getMessageProperties().getConsumerQueue();
        String userId = queueName.substring(queueName.lastIndexOf("_") + 1);
        // 获取用户的 channel
        io.netty.channel.Channel userChannel = NoticeWebSocketHandler.userChannelMap.get(userId);
        // 判断用户是否在线,不在线则不消费
        if (userChannel != null) {
            // 消费数据
            Map<String, Integer> info = new HashMap<>();
            info.put("sysNoticeCount", 1);
            System.out.println("监听消费: " + 1);
            ResultEntity<Map<String, Integer>> response = ResultEntity.SUCCESS(info);
            // 把数据通过WebSocket连接主动推送用户
            userChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)));
        }
    }
}
